package com.nycreativity.elecreativity.controller


import com.nycreativity.elecreativity.entity.ResultData
import com.nycreativity.elecreativity.entity.cons.CommonURLConstants
import com.nycreativity.elecreativity.entity.param.PageParam
import com.nycreativity.elecreativity.entity.param.shoppingcart.ShoppingCartAddParam
import com.nycreativity.elecreativity.entity.param.shoppingcart.ShoppingCartUpdateParam
import com.nycreativity.elecreativity.entity.vo.shoppingcart.ShoppingCartVO
import com.nycreativity.elecreativity.service.ShoppingCartService
import com.nycreativity.elecreativity.util.usersession.UserContext
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-03-11
 */
@RestController
@RequestMapping(CommonURLConstants.SHOPPING_CART_PREFIX)
@Api(tags = ["购物车相关接口"])
class ShoppingCartController {

    @Autowired
    lateinit var shoppingCartService: ShoppingCartService

    @PostMapping
    @ApiOperation("当前用户购物车信息添加")
    fun addCartWithGoods(
        @RequestBody
        shoppingCartAddParams: Array<ShoppingCartAddParam>
    ): ResultData<Boolean> {
        if (shoppingCartAddParams.isEmpty()) {
            return ResultData.FAILED("请传入商品信息")
        }
        return if (UserContext.get() != null && shoppingCartService.addShoppingCart(shoppingCartAddParams))
            ResultData.SUCCESS("购物车数据添加成功")
        else
            ResultData.FAILED("购物车数据添加失败")
    }

    @GetMapping
    @ApiOperation("查询当前用户的购物车")
    fun getShoppingCart(pageParam: PageParam): ResultData<ShoppingCartVO> {
        return ResultData.SUCCESS(data = shoppingCartService.queryShoppingCart(pageParam))
    }

    @DeleteMapping
    @ApiOperation("删除当前用户购物车的一件或多件商品")
    fun removeShoppingCartItems(skuIds: Array<Long>): ResultData<Any> {
        return if (shoppingCartService.removeShoppingCartItems(skuIds))
            ResultData.SUCCESS()
        else
            ResultData.FAILED()
    }

    @PutMapping("{id}")
    @ApiOperation("修改购物车商品信息")
    fun updateShoppingCartItem(
        @PathVariable("id") id: Long,
        shoppingCartUpdateParam: ShoppingCartUpdateParam
    ): ResultData<Any> {
        return if (shoppingCartService.updateShoppingCartItem(id, shoppingCartUpdateParam))
            ResultData.SUCCESS()
        else
            ResultData.FAILED()
    }
}


